package com.jjb.www.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.hjq.base.BaseAdapter;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.layout.ShapeRecyclerView;
import com.hjq.shape.view.ShapeImageView;
import com.hjq.shape.view.ShapeTextView;
import com.jjb.www.R;
import com.jjb.www.app.AppFragment;
import com.jjb.www.app.TitleBarFragment;
import com.jjb.www.bean.BannerBean;
import com.jjb.www.bean.MessBean;
import com.jjb.www.http.api.AgencyListApi;
import com.jjb.www.http.api.AgencyRealNameApi;
import com.jjb.www.http.api.CurriculumSortApi;
import com.jjb.www.http.api.HomePosterApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.http.model.HttpList;
import com.jjb.www.http.model.HttpListData;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.activity.DryRrunActivity;
import com.jjb.www.ui.activity.GoRealNameActivity;
import com.jjb.www.ui.activity.HomeActivity;
import com.jjb.www.ui.activity.MeCertificateActivity;
import com.jjb.www.ui.activity.MeCurriculumActivity;
import com.jjb.www.ui.activity.MessageListActivity;
import com.jjb.www.ui.activity.PlanDetitleActivity;
import com.jjb.www.ui.activity.PreEmploymentActivity;
import com.jjb.www.ui.activity.PremiumCoursesActivity;
import com.jjb.www.ui.activity.PunchClockRecordActivity;
import com.jjb.www.ui.activity.ScanQrCodeActivity;
import com.jjb.www.ui.activity.SelectPostActivity;
import com.jjb.www.ui.activity.SignUpActivity;
import com.jjb.www.ui.activity.VipActivity;
import com.jjb.www.ui.adapter.AgencyAdapter;
import com.jjb.www.ui.adapter.BannerHomeListAdapter;
import com.jjb.www.ui.adapter.HomeMessageAdapter;
import com.jjb.www.ui.adapter.TabAdapter;
import com.jjb.www.widget.XCollapsingToolbarLayout;
import com.xj.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import java.util.ArrayList;
import java.util.List;

/**
 * author : Android CRG
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : 首页 Fragment
 */
public final class HomeFragment extends TitleBarFragment<HomeActivity>
        implements TabAdapter.OnTabListener, ViewPager.OnPageChangeListener,
        XCollapsingToolbarLayout.OnScrimsListener , BaseAdapter.OnItemClickListener {

    private XCollapsingToolbarLayout mCollapsingToolbarLayout;
    private MarqueeView mSortMarqueevItem;
    private ShapeImageView mImgJxbm;
    private ShapeImageView mImgGqpx;
    private ShapeImageView mImgMnks;
    private ShapeLinearLayout mLlCjcx;
    private ShapeLinearLayout mLlWdzs;
    private ShapeLinearLayout mLlWdkc;
    private ShapeLinearLayout mLlMnks;
    private RecyclerView mTabView;
    private ShapeRecyclerView mRvAgency;
    private ShapeTextView mTvMore;
    private ShapeImageView mImgQcr;
    private ShapeLinearLayout mLlDaiban;
    private Banner mBanner;
    private String leftName = "";
    private String rightName = "";
    private BannerHomeListAdapter bannerListAdapter;
    private AgencyAdapter agencyAdapter;
    private ViewPager mViewPager;
    private TabAdapter mTabAdapter;
    private List<BannerBean> datas = new ArrayList<>();
    private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        mCollapsingToolbarLayout = findViewById(R.id.ctl_home_bar);
        mTabView = findViewById(R.id.rv_home_tab);
        mLlDaiban = findViewById(R.id.ll_daiban);
        mViewPager = findViewById(R.id.vp_home_pager);
        mSortMarqueevItem = findViewById(R.id.sort_marqueev_item);
        mImgJxbm = findViewById(R.id.img_jxbm);
        mImgGqpx = findViewById(R.id.img_gqpx);
        mImgMnks = findViewById(R.id.img_mnks);
        mLlCjcx = findViewById(R.id.ll_cjcx);
        mLlWdzs = findViewById(R.id.ll_wdzs);
        mLlWdkc = findViewById(R.id.ll_wdkc);
        mLlMnks = findViewById(R.id.ll_mnks);
        mBanner = findViewById(R.id.banner);
        mTvMore = findViewById(R.id.tv_more);
        mRvAgency = findViewById(R.id.rv_agency);
        mImgQcr = findViewById(R.id.img_qcr);
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        mViewPager.addOnPageChangeListener(this);
        mTabAdapter = new TabAdapter(getAttachActivity(), TabAdapter.TAB_MODE_DESIGN, false);
        mTabView.setAdapter(mTabAdapter);
        mTabAdapter.setOnTabListener(this);

        // 给这个 ToolBar 设置顶部内边距，才能和 TitleBar 进行对齐
//        ImmersionBar.setTitleBar(getAttachActivity(), mToolbar);
        bannerListAdapter = new BannerHomeListAdapter(getContext(),datas);
        mBanner.setAdapter(bannerListAdapter);
        mBanner.setIndicator(new RectangleIndicator(getContext()));
        //设置渐变监听
        mCollapsingToolbarLayout.setOnScrimsListener(this);
        mRvAgency.setLayoutManager(new LinearLayoutManager(getContext()));
        agencyAdapter = new AgencyAdapter(getContext());
        agencyAdapter.setOnItemClickListener(this);
        mRvAgency.setAdapter(agencyAdapter);

        setOnClickListener(mTvMore,mImgQcr,mSortMarqueevItem,mImgJxbm,mImgGqpx,mImgMnks,mLlCjcx,mLlWdzs,mLlWdkc,mLlMnks);
        getStatusBarConfig().statusBarDarkFont(true).fitsSystemWindows(true).statusBarColor(R.color.white).init();
    }
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId==R.id.sort_marqueev_item){
            //滚动消息
            startActivity(MessageListActivity.class);
        }else if (viewId==R.id.img_jxbm){
            if (AppConfig.getInstance().getUserBean().getUser().getIs_auth()==0){
                toast("");
                return;
            }
            //继续教育报名
            startActivity(SignUpActivity.class);
        }else if (viewId==R.id.img_gqpx){
            //岗前培训
            startActivity(PreEmploymentActivity.class);
        }else if (viewId==R.id.img_mnks){
            //模拟考试
            Intent intent = new Intent();
            intent.putExtra("leftName",leftName);
            intent.putExtra("rightName",rightName);
            intent.putExtra("fromType","home");
            intent.setClass(getContext(),SelectPostActivity.class);
            startActivity(intent);
        }else if (viewId==R.id.ll_cjcx){
            startActivity(PunchClockRecordActivity.class);
            //成绩查询
//            startActivity(VipActivity.class);
        }else if (viewId==R.id.ll_wdzs){
            //我的证书
            startActivity(MeCertificateActivity.class);
        }else if (viewId==R.id.ll_wdkc){
            //我的课程
            startActivity(MeCurriculumActivity.class);
        }else if (viewId==R.id.ll_mnks){
            //模考记录
            startActivity(DryRrunActivity.class);
        }else if (viewId==R.id.img_qcr){
            //二维码扫描
            startActivity(ScanQrCodeActivity.class);
        }else if (viewId==R.id.tv_more){
            //更多
            startActivity(PremiumCoursesActivity.class);
        }
    }
    @Override
    protected void initData() {
        if ("".equals(AppConfig.getInstance().getToken())){
            //未登录
            mLlDaiban.setVisibility(View.GONE);
        }else {
            mLlDaiban.setVisibility(View.VISIBLE);
            if (AppConfig.getInstance().getUserBean().getUser().getIs_auth()==0){
                //未实名
                getRealName();
            }else {
                //已实名
                //代办事项
                getAgencyList();
            }
        }
        //banner 滚动消息
        getBannerData();
        //课程列表分类
        getCurriculumSort();
    }

    private void getCurriculumSort() {
        EasyHttp.get(this)
                .api(new CurriculumSortApi())
                .request(new HttpCallback<HttpList<CurriculumSortApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpList<CurriculumSortApi.Bean> data) {
                        mPagerAdapter.addFragment(CourseListFragment.newInstance("0"), "推荐");
                        mTabAdapter.addItem("推荐");
                        for (CurriculumSortApi.Bean bean:data.getData()) {
                            mPagerAdapter.addFragment(CourseListFragment.newInstance(bean.getId()+""), bean.getTitle());
                            mTabAdapter.addItem(bean.getTitle());
                        }
                        mViewPager.setAdapter(mPagerAdapter);

                    }

                });
    }

    /**
     * 实名
     */
    private void getRealName() {
        EasyHttp.get(this)
                .api(new AgencyRealNameApi())
                .request(new HttpCallback<HttpList<AgencyRealNameApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpList<AgencyRealNameApi.Bean> data) {
                        List<AgencyListApi.Bean> list= new ArrayList<>();
                        for (AgencyRealNameApi.Bean sm:data.getData()) {
                            AgencyListApi.Bean bean = new AgencyListApi.Bean();
                            bean.setId(sm.getId());
                            bean.setType(sm.getType());
                            bean.setLabel(sm.getLabel());
                            bean.setTitle(sm.getTitle());
                            bean.setViceTitle(sm.getViceTitle());
                            bean.setBtnText(sm.getBtnText());
                            bean.setBtnType(sm.getBtnType());
                            bean.setPath(sm.getPath());
                            bean.setIsPlaying(sm.getIsPlaying());
                            list.add(bean);
                        }
                        agencyAdapter.setData(list);
                    }

                });
    }
    //岗前蓝 继教红 其余黄
    private void getAgencyList() {
        EasyHttp.get(this)
                .api(new AgencyListApi())
                .request(new HttpCallback<HttpList<AgencyListApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpList<AgencyListApi.Bean> data) {
                        agencyAdapter.setData(data.getData());
                    }
                });
    }

    private void getBannerData() {
        EasyHttp.get(this)
                .api(new HomePosterApi()
                        .setRegion_id("32")
                        .setType("1"))
                .request(new HttpCallback<HttpData<HomePosterApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<HomePosterApi.Bean> data) {
                        Log.e("HomePosterApi",data+"");
                        for (HomePosterApi.Bean.AdvertDTO advertDTO:data.getData().getAdvert()) {
                            BannerBean bean = new BannerBean();
                            bean.setImg(advertDTO.getImg());
                            bean.setPath(advertDTO.getPath());
                            bean.setType(advertDTO.getType()+"");
                            datas.add(bean);
                        }
                        bannerListAdapter.setDatas(datas);
                        List<MessBean> messBeanList = new ArrayList<>();

                        for (HomePosterApi.Bean.NoticeDTO.NewTimeDataArrDTO newTimeDataArrDTO : data.getData().getNotice().getNewTimeDataArr()) {
                            MessBean messBean = new MessBean();
                            messBean.setData(newTimeDataArrDTO.getTitle());
                            messBeanList.add(messBean);
                        }
                        HomeMessageAdapter messageListAdapter = new HomeMessageAdapter(getContext(), R.layout.item_mess_list, messBeanList);

                        messageListAdapter.setOnItemClickListener((position, view) -> {
                            startActivity(MessageListActivity.class);
                        });
                        mSortMarqueevItem.setAdapter(messageListAdapter);

                    }

                });
    }


    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public boolean isStatusBarDarkFont() {
        return mCollapsingToolbarLayout.isScrimsShown();
    }

    /**
     * {@link TabAdapter.OnTabListener}
     */

    @Override
    public boolean onTabSelected(RecyclerView recyclerView, int position) {
        mViewPager.setCurrentItem(position);
        return true;
    }



    /**
     * {@link ViewPager.OnPageChangeListener}
     */

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (mTabAdapter == null) {
            return;
        }
        mTabAdapter.setSelectedPosition(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    /**
     * CollapsingToolbarLayout 渐变回调
     * <p>
     * {@link XCollapsingToolbarLayout.OnScrimsListener}
     */
    @SuppressLint("RestrictedApi")
    @Override
    public void onScrimsStateChange(XCollapsingToolbarLayout layout, boolean shown) {
        getStatusBarConfig().statusBarColor(shown ? R.color.color_F5F5F5 : R.color.white).init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewPager.setAdapter(null);
        mViewPager.removeOnPageChangeListener(this);
        mTabAdapter.setOnTabListener(null);
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        if (AppConfig.getInstance().getUserBean().getUser().getIs_auth()==0){
            //未实名
            startActivity(GoRealNameActivity.class);
        }else {
            if (agencyAdapter.getItem(position).getType()==3||agencyAdapter.getItem(position).getType()==2){
                HomeActivity.start(getContext(),StudyFragment.class,position);
            }
        }
    }
}